package com.change.core.jackson;

import com.change.core.convert.DateFormatter;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 * LocalDateTimeSerializer
 *
 * @author linqunxun
 * @date 2021/9/10 10:24 上午
 */
public class LocalDateTimeSerializer extends StdSerializer<LocalDateTime> {
    public LocalDateTimeSerializer() {
        super(LocalDateTime.class);
    }

    @Override
    public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        if (value != null) {
            if (provider.isEnabled(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)) {
                final long mills = value.atZone(ZoneOffset.systemDefault()).toInstant().toEpochMilli();
                gen.writeNumber(mills);
            } else {
                gen.writeString(value.format(DateFormatter.LOCAL_DATE_TIME));
            }
        } else {
            gen.writeNull();
        }
    }
}
